/*
 * @Author: actor
 * @Date: 2023-12-14 14:47:37
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-19 10:13:03
 * @FilePath: \i-hos-app\shared\emr\src\hooks\usePdfHtml.ts
 * @Description: 页面转成pdf
 */
import { ref, Ref } from 'vue'
import html2Canvas from 'html2canvas'
import JsPDF, { jsPDF } from 'jspdf'
import { generateMixed } from '../utils/index'

export const usePdfHtml = (ele: any, pdfFileType: string, pdfFileName?: string): any => {
  /**
   * ele： 需要转成pdf的html
   * type: 转成pdf后的操作类型（如：'save': 保存下载pdf文件, 'preview': 预览转成的pdf, 'file': 返回pdf的file文件）
   * pdfFileName： 转成pdf的名字（不传字自动随机生成一个名字）
   * */
  let pdfSave: Ref<any> = ref(null)
  if (!pdfFileName) pdfFileName = generateMixed(20)
  html2Canvas(ele, {
    // dpi: window.devicePixelRatio * 4,
    scale: 4,
    useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
    allowTaint: false,
    height: ele.offsetHeight,
    width: ele.offsetWidth,
    windowWidth: document.body.scrollWidth,
    windowHeight: document.body.scrollHeight,
  }).then((canvas: HTMLCanvasElement) => {
    //未生成pdf的html页面高度
    let leftHeight: number = canvas.height,
      a4Width: number = 595.28,
      a4Height: number = 841.89,
      a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height), //一页pdf显示html页面生成的canvas高度;
      position: number = 0, //pdf页面偏移
      pageData: string = canvas.toDataURL('image/jpeg', 1.0),
      pdf: jsPDF = new JsPDF('p', 'pt', 'a4'),
      index: number = 1,
      canvas1: HTMLCanvasElement = document.createElement('canvas'),
      height: number

    pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen')

    function createImpl(canvas: any) {
      if (leftHeight > 0) {
        index++
        let checkCount: number = 0

        if (leftHeight > a4HeightRef) {
          let i: number = position + a4HeightRef
          for (i = position + a4HeightRef; i >= position; i--) {
            let isWrite: boolean = true
            for (let j: number = 0; j < canvas.width; j++) {
              let c: any = canvas.getContext('2d').getImageData(j, i, 1, 1).data
              if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                isWrite = false
                break
              }
            }
            if (isWrite) {
              checkCount++
              if (checkCount >= 10) {
                break
              }
            } else {
              checkCount = 0
            }
          }
          height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef)
          if (height <= 0) {
            height = a4HeightRef
          }
        } else {
          height = leftHeight
        }

        canvas1.width = canvas.width
        canvas1.height = height

        let ctx: any = canvas1.getContext('2d')
        ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height)
        // let pageHeight = Math.round(a4Width / canvas.width * height);
        if (position != 0) {
          pdf.addPage()
        }
        pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, (a4Width / canvas1.width) * height)

        leftHeight -= height
        position += height
        if (leftHeight > 0) {
          //添加全屏水印
          // const base64 = ''
          // for(let i=0;i<6;i++){
          //   for(let j=0;j<5;j++){
          //     const  left = (j*120)+20;
          //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
          //   }
          // }
          setTimeout(createImpl, 500, canvas)
        } else {
          if (pdfFileType == 'save') {
            pdfSave.value = pdf.save(pdfFileName + '.pdf')
          } else if (pdfFileType == 'preview') {
            convertFile(pdf.output('dataurlstring'), pdfFileName as string)
          }
        }
      }
    }
    //当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < a4HeightRef) {
      pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, (a4Width / canvas.width) * leftHeight)
      if (pdfFileType == 'save') {
        pdfSave.value = pdf.save(pdfFileName + '.pdf')
      } else if (pdfFileType == 'preview') {
        convertFile(pdf.output('dataurlstring'), pdfFileName as string)
      }
    } else {
      try {
        pdf.deletePage(0)
        setTimeout(createImpl, 500, canvas)
      } catch (err) {
        console.log(err)
      }
    }
  })

  // 转file文件
  const convertFile = (urlData: any, filename: string) => {
    // if (typeof urlData != 'string') {
    //   this.$toast("urlData不是字符串")
    //   return;
    // }
    let arr: any = urlData.split(','),
      type: any = arr[0].match(/:(.*?);/)[1],
      fileExt: any = type.split('/')[1],
      bstr: string = atob(arr[1]),
      n: number = bstr.length,
      u8arr: Uint8Array = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename + '.' + fileExt, { type: type })
  }
}
